package base

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"go.mongodb.org/mongo-driver/bson"
	"rewords-server-2024/utility/ztime"

	"github.com/gogf/gf/v2/errors/gerror"

	"rewords-server-2024/api/base/system"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/library/ecode"
	"rewords-server-2024/internal/model/input/form"
	"rewords-server-2024/internal/service"
)

func (c *ControllerSystem) SysUserUpdate(ctx context.Context, req *system.SysUserUpdateReq) (res *system.SysUserUpdateRes, err error) {
	// 使用 Builder 构建更新文档
	updateFields := form.NewBuilder().
		SetIfNotEmpty("username", req.Username).
		SetIfNotEmpty("email", req.Email).
		SetIfNotEmpty("phone", req.Phone).
		SetIfNotEmpty("openid", req.Openid).
		SetIfNotEmpty("nickname", req.Nickname).
		SetIfNotEmpty("avatar", req.Avatar).
		SetIfNotEmpty("union_id", req.UnionId).
		SetIfNotZero("level", req.Level).
		SetIfNotZero("points", req.Points).
		SetIfNotZero("role", req.Role).
		SetIfNotZero("status", req.Status).
		Set("updated_at", ztime.GetLocalTime()). // 使用 time.Now()
		Build()

	// 执行更新操作
	result, err := service.Mgx().UpdateOne(ctx,
		consts.CUser,
		bson.M{"uid": req.Uid},
		bson.M{"$set": updateFields},
	)
	if err != nil {
		g.Log().Error(ctx, "Update error:", err)
		return nil, gerror.NewCode(ecode.InvalidParams)
	}

	if result.MatchedCount == 0 {
		return nil, gerror.NewCode(ecode.DataNotFound)
	}

	return &system.SysUserUpdateRes{}, nil
}
